/**
 * Created by jaliu on 2015/2/13.
 */

var adminUsers = mongoose.model('backoffice_adminusers');
var async = require('async');
var Community = mongoose.model('community');
var toolUtil = require('../../common/utils/toolUtil');

/**
 * userService.js
 * 后台管理用户登录
 *author：chenjinzhuan
 * */
exports.adminUserLoginService = function (input, callback) {
    var loginId = input.loginId;
    var password = input.password;
    adminUsers.find({'loginId': loginId, 'password': password, role: {$ne: 'Guest'}}, callback);
};

exports.adminUserCreateService = function (input, callback) {
    var adminUser = new adminUsers();
    adminUser.loginId = input.loginId;
    adminUser.userName = input.userName;
    adminUser.password = input.password;
    adminUser.role = input.role;
    adminUser.communities = input.communities;
    adminUser.appuser = input.appuser;
    adminUser.save(callback);
};

exports.adminUserDeleteService = function (loginId, callback) {
    adminUsers.findOneAndRemove({loginId: loginId}, callback);
};

exports.adminUserUpdateService = function (loginId, input, callback) {

    async.series([
        function (callbackInner) {
            adminUsers.findOne({loginId: loginId}, function (err, adminUser) {
                if (adminUser.appuser != null && adminUser.appuser.huanxinUserName != null) {
                    async.series([
                        function (callback1) {
                            async.each(adminUser.communities, function (communityId, c1) {
                                Community.findOne({_id: communityId}, 'chatGroupId', function (err, result) {
                                    toolUtil.getAndCacheHuanXinToken(function (err, token) {
                                        var args = {
                                            data: {},
                                            headers: {
                                                "Content-Type": "application/json",
                                                "Authorization": "Bearer " + token
                                            }
                                        };
                                        restClient.delete("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + result.chatGroupId + "/users/" + adminUser.appuser.huanxinUserName, args, function (data, response) {
                                            c1();
                                        })
                                    });
                                });
                            }, function (err) {
                                callback1();
                            })
                        },
                        function (callback1) {
                            async.each(input.communities, function (communityId, c1) {
                                Community.findOne({_id: communityId}, 'chatGroupId', function (err, result) {
                                    toolUtil.getAndCacheHuanXinToken(function (err, token) {
                                        var args = {
                                            data: {},
                                            headers: {
                                                "Content-Type": "application/json",
                                                "Authorization": "Bearer " + token
                                            }
                                        };
                                        restClient.post("https://a1.easemob.com/66xiaoqu/" + huanxinEnv + "/chatgroups/" + result.chatGroupId + "/users/" + adminUser.appuser.huanxinUserName, args, function (data, response) {
                                            c1();
                                        })
                                    });
                                });
                            }, function (err) {
                                callback1();
                            })
                        }
                    ], callbackInner)
                } else {
                    callbackInner();
                }
            }).populate('appuser', 'huanxinUserName')
        },
        function (callbackInner) {
            adminUsers.update({loginId: loginId},
                {
                    $set: {
                        'userName': input.userName,
                        'role': input.role,
                        'password': input.password,
                        'communities': input.communities,
                        'appuser': input.appuser
                    }
                }, callbackInner);
        }
    ], callback);
};

exports.adminUserFindById = function (loginId, callback) {
    adminUsers.findOne({loginId: loginId}, function (err, results) {
        if (results != null) {
            callback(null, results);
        }
    }).populate("communities", 'communityName').populate("appuser", 'mobilePhone');
};

exports.adminUserListService = function (startPage, pageSize, callback) {
    async.series([
        function (callbackInner) {
            adminUsers.count({}, callbackInner);
        },
        function (callbackInner) {
            adminUsers.find({}).populate("appuser", 'mobilePhone').populate("communities", "_id communityName").sort('domain').skip(startPage).limit(pageSize).exec(callbackInner);
        }
    ], callback);
};

